// import { uid } from 'uid'

const store = {
  achievement: {
    create_time: false,
    student: false,
    score: false
  }
}
let db = ''

const initDb = (dbName, version) => {
  const req = indexedDB.open(dbName, version)
  // 操作成功
  req.onsuccess = function (event) {
    db = event.target.result // 数据库对象
    console.log('数据库打开成功')
  }
  // 操作失败
  req.onerror = function (event) {
    console.log('数据库打开失败')
  }
  // 创建表和索引
  req.onupgradeneeded = function (event) {
    console.log('更新')
    // 数据库创建或升级的时候会触发
    db = event.target.result // 数据库对象
    for (const storeName in store) {
      let objectStore
      if (!db.objectStoreNames.contains(storeName)) {
        objectStore = db.createObjectStore(storeName, { keyPath: 'id', autoIncrement: true }) // 创建表
        for (const name in store[storeName]) {
          const value = store[storeName][name]
          objectStore.createIndex(name, name, { unique: value }) // 创建索引
        }
      }
    }
  }
}
export default (Vue) => {
  initDb('dataclass', 1)
  // console.log(db)
  // const transaction = db.transaction(['student'], 'readwrite')
  // const objectStore = transaction.objectStore('student') // params 表名
  // window.objectStore = objectStore
  Vue.prototype.$db = {
    add (storeName, params) {
      const transaction = db.transaction([storeName], 'readwrite')
      const objectStore = transaction.objectStore(storeName) // params 表名
      objectStore.add(params)
    },
    select (storeName) {
      const transaction = db.transaction([storeName], 'readwrite')
      const objectStore = transaction.objectStore(storeName) // params 表名
      return objectStore.getAll()
    }
  }
}
